<template>
  <el-card>
    <el-form ref="queryFormRef" :model="queryParams" :inline="true">
      <el-form-item label="类型" prop="type">
        <el-select
          v-model="queryParams.type"
          placeholder="全部"
          clearable
          style="width: 200px"
        >
          <el-option
            v-for="(item, index) in typeMap"
            :key="index"
            :label="item"
            :value="index"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="可重复获取" prop="isRepeat">
        <el-select
          v-model="queryParams.isRepeat"
          placeholder="全部"
          clearable
          style="width: 200px"
        >
          <el-option :value="true" label="是" />
          <el-option :value="false" label="否" />
        </el-select>
      </el-form-item>
      <el-form-item label="默认配置" prop="isDefault">
        <el-select
          v-model="queryParams.isDefault"
          placeholder="全部"
          clearable
          style="width: 200px"
        >
          <el-option :value="true" label="是" />
          <el-option :value="false" label="否" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="isEnable">
        <el-select
          v-model="queryParams.isEnable"
          placeholder="全部"
          clearable
          style="width: 200px"
        >
          <el-option :value="true" label="启用" />
          <el-option :value="false" label="禁用" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button class="filter-item" type="primary" @click="handleQuery">
          <i-ep-search />
          搜索
        </el-button>
        <el-button @click="resetQuery"> <i-ep-refresh />重置 </el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card>
    <el-button
      type="success"
      @click="openDialog(null)"
      v-hasPerm="['sys:reward:add']"
      >新增</el-button
    >
  </el-card>
  <el-card>
    <el-table
      :data="tableData"
      v-loading="loading"
      @selection-change="handleSelectionChange"
      border
      style="width: 100%"
    >
      <el-table-column
        fixed
        type="index"
        :index="indexMethod"
        label="序号"
        width="70"
      />
      <el-table-column prop="code" label="代码" width="200" />
      <el-table-column prop="name" label="名称" width="200" />
      <el-table-column prop="rewardValue" label="奖励值" width="100" />
      <el-table-column prop="type" label="类型" width="200" />
      <el-table-column prop="target" label="累计值" width="100" />
      <el-table-column prop="isRepeat" label="可重复获取" width="100">
        <template #default="scope">
          <el-tag v-if="scope.row.isRepeat == 1" type="success">是</el-tag>
          <el-tag v-else type="info">否</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="isDefault" label="默认配置" width="100">
        <template #default="scope">
          <el-tag v-if="scope.row.isDefault == 1" type="success">是</el-tag>
          <el-tag v-else type="info">否</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="isEnable" label="启用" width="100">
        <!--        <template #default="scope">-->
        <!--          <el-tag v-if="scope.row.isEnable == 1" type="success">正常</el-tag>-->
        <!--          <el-tag v-else type="info">禁用</el-tag>-->
        <!--        </template>-->
        <template #default="scope">
          <el-switch
            v-model="scope.row.isEnable"
            class="ml-2"
            style="

              --el-switch-on-color: #13ce66;
              --el-switch-off-color: #ff4949;
            "
            v-hasPerm="['sys:reward:enable']"
            @change="enable(scope.row.id)"
          />
        </template>
      </el-table-column>

      <el-table-column fixed="right" label="操作" width="200">
        <template #default="scope">
          <el-button
            type="warning"
            @click.stop="openDialog(scope.row)"
            v-hasPerm="['sys:reward:update']"
            >修改</el-button
          >
          <el-button
            type="danger"
            @click="deleteClick(scope.row.id)"
            v-hasPerm="['sys:reward:delete']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页搜索 -->
    <div
      style="
        display: flex;
        justify-content: center;
        width: 100%;
        margin-top: 15px;
      "
    >
      <el-pagination
        background
        layout="sizes, prev,slot, next, jumper"
        :page-count="pageTotal"
        :page-sizes="[10, 20, 30, 50]"
        :current-page="activePager"
        @update:current-page="pageChange"
        @update:page-size="sizeChange"
        :default-current-page="1"
        :default-page-size="10"
      >
        <div class="pagination">
          <span
            class="pagination__item"
            :class="{ active: activePager === pager }"
            v-for="pager in pageArr"
            :key="pager"
            @click="pageChange(pager)"
          >
            {{ pager }}
          </span>
        </div>
      </el-pagination>
    </div>
    <!-- 分页搜索 -->
  </el-card>

  <el-dialog
    :title="dialog.title"
    v-model="dialog.visible"
    width="600px"
    @closed="closeDialog"
  >
    <el-form
      ref="rewardFormRef"
      :model="formData"
      :rules="rules"
      label-width="80px"
    >
      <el-form-item label="名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入名称" />
      </el-form-item>
      <el-form-item label="奖励值" prop="rewardValue">
        <el-input-number
          v-model="formData.rewardValue"
          controls-position="right"
          style="width: 100px"
          :min="0"
        />
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-select v-model="formData.type" placeholder="请选择类型">
          <el-option
            v-for="(item, index) in typeMap"
            :key="index"
            :label="item"
            :value="index"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="目标值" prop="target">
        <el-input-number
          v-model="formData.target"
          controls-position="right"
          style="width: 100px"
          :min="0"
        />
      </el-form-item>
      <el-form-item label="是否可重复获取">
        <el-radio-group v-model="formData.isRepeat">
          <el-radio :label="true">是</el-radio>
          <el-radio :label="false">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="是否为默认配置">
        <el-radio-group v-model="formData.isDefault">
          <el-radio :label="true">是</el-radio>
          <el-radio :label="false">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="启用">
        <el-radio-group v-model="formData.isEnable">
          <el-radio :label="true">正常</el-radio>
          <el-radio :label="false">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleSubmit"> 确 定 </el-button>
        <el-button @click="closeDialog"> 取 消 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { rewardList, parameter, queryForm } from "../../../api/reward/type";
import { onMounted, reactive, ref } from "vue";
import {
  addReward,
  deleteReward,
  enableReward,
  getReward,
  getRewardList,
  getRewardType,
  updateReward,
} from "../../../api/reward/index";

const loading = ref(false);

let tableData = ref<rewardList[]>();
const dialogEdit = ref(false);

//总共页数
const pageTotal = ref(0);
//后端传来的页码数组
const pageArr = ref([]);
//当前页码
const activePager = ref(1);

const dialogAdd = ref(false);

const ids = ref([]);

const dialog = reactive<DialogOption>({
  visible: false,
});

const rewardFormRef = ref(ElForm);
const queryFormRef = ref(ElForm);

let typeMap = ref(Map);

const rules = reactive({});

let formData = reactive<rewardList>({
  rewardValue: 0,
  target: 0,
  isRepeat: false,
  isDefault: false,
  isEnable: false,
});

let keys = reactive<parameter>({
  pageNum: 1,
  pageSize: 10,
});

const queryParams = reactive<queryForm>({
  type: "",
  isRepeat: true,
  isDefault: true,
  isEnable: true,
  pageNum: 1,
  pageSize: 10,
});

async function enable(id: number) {
  await enableReward(id).then(({ data }) => {
    console.log(data);
  });
}

async function getType() {
  await getRewardType().then(({ data }) => {
    typeMap.value = data;
  });
}

const indexMethod = (index: number) => {
  return index + 10 * activePager.value - 9;
};

/**
 * 行checkbox change事件
 */
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}

/**
 * 删除
 */

async function deleteClick(id: number) {
  await ElMessageBox.confirm("确认删除?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    deleteReward(id).then(() => {
      ElMessage.success("删除成功");
      resetReward();
    });
  });
}

/**
 * 添加
 */

function addClick() {
  dialogAdd.value = true;
}

/**
 * 刷新
 */
function resetReward() {
  handleData();
}

/**
 * 获取奖励列表
 */
async function handleData() {
  loading.value = true;
  await getType();
  await getRewardList(keys)
    .then(({ data }) => {
      console.log(data.data);
      tableData.value = data.data.list;
      pageTotal.value = data.navigatepageNums[data.navigatepageNums.length - 1];
      pageArr.value = data.navigatepageNums;
    })
    .catch((error) => {
      console.error("Error:", error);
    })
    .finally(() => {
      loading.value = false;
    });
}

async function handleQuery() {
  loading.value = true;
  await getRewardList(queryParams)
    .then(({ data }) => {
      console.log(data.data);
      tableData.value = data.data.list;
      pageTotal.value = data.navigatepageNums[data.navigatepageNums.length - 1];
      pageArr.value = data.navigatepageNums;
    })
    .catch((error) => {
      console.error("Error:", error);
    })
    .finally(() => {
      loading.value = false;
    });
}

/**
 * 重置查询
 */
function resetQuery() {
  queryFormRef.value.resetFields();
  queryFormRef.value.clearValidate();
  handleData();
}

function pageChange(pageNum: number) {
  keys.pageNum = pageNum;
  activePager.value = pageNum;
  handleData();
}

function sizeChange(sizeNum: number) {
  keys.pageSize = sizeNum;
  handleData();
}

/**
 * 关闭弹窗
 */
function closeDialog() {
  dialog.visible = false;
  resetForm();
}

/**
 * 重置表单
 */
function resetForm() {
  rewardFormRef.value.resetFields();
  rewardFormRef.value.clearValidate();

  formData.id = 0;
  formData.rewardValue = 0;
  formData.target = 1;
  formData.isRepeat = false;
  formData.isDefault = false;
  formData.isEnable = false;
}

/**
 * 打开弹窗
 *
 * @param rewardId 奖励id
 */
async function openDialog(reward: any) {
  dialog.visible = true;
  if (reward && reward.id) {
    dialog.title = "修改奖励";
    Object.assign(formData, reward);
    // formData = reward
  } else {
    dialog.title = "新增奖励";
  }
}

/**
 * 表单提交
 */
function handleSubmit() {
  rewardFormRef.value.validate((valid: any) => {
    if (valid) {
      const id = formData.id;
      loading.value = true;
      if (id) {
        // 处理 type 字段替换
        const typeMapEntries = Object.entries(typeMap.value);
        typeMapEntries.forEach(([key, value]) => {
          if (formData.type === value) {
            formData.type = key;
          }
        });

        updateReward(formData)
          .then(() => {
            ElMessage.success("修改成功");
            closeDialog();
            handleData();
          })
          .finally(() => (loading.value = false));
      } else {
        addReward(formData)
          .then(() => {
            ElMessage.success("新增成功");
            closeDialog();
            handleData();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

onMounted(() => {
  handleData();
});
</script>
